function hfile = srf_SaveAsVTK(hfile, vtkfile)
% SRF::SaveAsVTK  - create a VTK file from a surface
%
% FORMAT:       srf.SaveAsVTK(vtkfile);
%
% Input fields:
%
%       vtkfile     filename of VTK file to write

% Version:  v0.7b
% Build:    7090215
% Date:     Sep-02 2006, 3:37 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% check input arguments
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'srf') || ...
   ~ischar(vtkfile) || ...
    isempty(vtkfile)
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);
vtkfile = vtkfile(:)';

% try to open file for output (binary write, big-endian)
fid = fopen(vtkfile, 'wb', 'ieee-be');
if fid < 1
    error( ...
        'BVQXfile:FileNotWritable', ...
        'Given filename is not writable.' ...
    );
end

% write header
fwrite(fid, ['# vtk DataFile Version 3.0' char(10)], 'char');
fwrite(fid, ['vtk output' char(10)], 'char');
fwrite(fid, ['BINARY' char(10)], 'char');
fwrite(fid, ['DATASET POLYDATA' char(10)], 'char');

% write vertices
numvert = bc.NrOfVertices;
fwrite(fid, [sprintf('POINTS %d float', numvert) char(10)], 'char');
fwrite(fid, ...
    (bc.VertexCoordinate' - ...
     bc.MeshCenter' * ones(1, numvert)), ...
    'single');
fwrite(fid, char(10), 'char');

% write triangles
numtri = bc.NrOfTriangles;
fwrite(fid, [sprintf('POLYGONS %d %d', numtri, 4 * numtri) char(10)], 'char');
fwrite(fid, ...
    [3 * ones(1, numtri); bc.TriangleVertex' - 1], ...
    'int32');
fwrite(fid, char(10), 'char');

% write footer
fwrite(fid, [sprintf('CELL_DATA %d', numtri) char(10)], 'char');
fwrite(fid, [sprintf('POINT_DATA %d', numvert) char(10)], 'char');

% close file
fclose(fid);
